package org.mg.engine;

import java.io.File;
import java.io.IOException;

public class Scanner {

    public static void scan(String packageName) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        String path = getSrcPath() + packageToDir(packageName);
        File dir=new File(path);
        File[] files=dir.listFiles();
        Class<?> clazz = null;
        for(File f : files){
            if(f.isDirectory()){
                String childName=packageName+"."+f.getName();
                scan(childName);
            }else{
                clazz = Class.forName(packageName+"."+f.getName().split("\\.")[0]);
                String name = clazz.getName();
                Object bean = clazz.newInstance();
                InstructFactory.setBean(getName(name),bean);
                InstructFactory.setBean(clazz,bean);
            }
        }
    }

    /**
     获取当前路径
     */
    public static String getSrcPath() throws IOException {
        String path=System.getProperty("user.dir") + "/message-engine/src/main/java" ;
        return path;
    }

    /**
     *package转换为路径格式
     */
    public static String packageToDir(String packageName){
        String[] array=packageName.split("\\.");
        StringBuffer sb=new StringBuffer();
        for(String str:array){
            sb.append(File.separator).append(str);
        }
        return sb.toString();
    }

    public static String getName (String packageName) {
        String name = packageName.substring(packageName.lastIndexOf(".")+1);
        String first = name.substring(0,1);
        return first.toLowerCase() + name.substring(1);
    }
}
